import React from 'react';
import { Card, Avatar, Typography, Tag, Space } from 'antd';
import { UserOutlined, RobotOutlined, WarningOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism';
import dayjs from 'dayjs';

const { Text } = Typography;

const MessageBubble = ({ message, isUser = false }) => {
  const {
    content,
    timestamp,
    confidence_score,
    has_safety_warning,
    safety_info
  } = message;

  // 格式化时间
  const formatTime = (time) => {
    if (!time) return '';
    return dayjs(time).format('HH:mm:ss');
  };

  // 自定义代码块渲染
  const CodeBlock = ({ node, inline, className, children, ...props }) => {
    const match = /language-(\w+)/.exec(className || '');
    return !inline && match ? (
      <SyntaxHighlighter
        style={tomorrow}
        language={match[1]}
        PreTag="div"
        {...props}
      >
        {String(children).replace(/\n$/, '')}
      </SyntaxHighlighter>
    ) : (
      <code className={className} {...props}>
        {children}
      </code>
    );
  };

  return (
    <div 
      className={`message-bubble ${isUser ? 'user' : 'assistant'}`}
      style={{
        display: 'flex',
        flexDirection: isUser ? 'row-reverse' : 'row',
        alignItems: 'flex-start',
        gap: '8px',
        marginBottom: '16px'
      }}
    >
      {/* 头像 */}
      <Avatar 
        icon={isUser ? <UserOutlined /> : <RobotOutlined />}
        style={{
          backgroundColor: isUser ? '#1890ff' : '#52c41a',
          flexShrink: 0
        }}
      />

      {/* 消息内容 */}
      <Card
        size="small"
        style={{
          maxWidth: '70%',
          backgroundColor: isUser ? '#e6f7ff' : '#fff',
          border: isUser ? '1px solid #91d5ff' : '1px solid #d9d9d9',
          borderRadius: '12px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
        }}
        bodyStyle={{ padding: '12px 16px' }}
      >
        {/* 安全警告 */}
        {has_safety_warning && safety_info && (
          <div style={{ marginBottom: '8px' }}>
            <Tag 
              icon={<WarningOutlined />} 
              color="warning"
              style={{ marginBottom: '8px' }}
            >
              安全提醒
            </Tag>
            {safety_info.message && (
              <Text type="warning" style={{ fontSize: '12px', display: 'block' }}>
                {safety_info.message}
              </Text>
            )}
          </div>
        )}

        {/* 消息内容 */}
        <div className="message-content">
          {isUser ? (
            <Text>{content}</Text>
          ) : (
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
              components={{
                code: CodeBlock,
                pre: ({ children }) => <div>{children}</div>
              }}
            >
              {content}
            </ReactMarkdown>
          )}
        </div>

        {/* 消息元信息 */}
        <div 
          style={{ 
            marginTop: '8px', 
            display: 'flex', 
            justifyContent: 'space-between',
            alignItems: 'center'
          }}
        >
          <Space size="small">
            {timestamp && (
              <Text type="secondary" style={{ fontSize: '11px' }}>
                {formatTime(timestamp)}
              </Text>
            )}
            
            {!isUser && confidence_score !== undefined && (
              <Text type="secondary" style={{ fontSize: '11px' }}>
                置信度: {(confidence_score * 100).toFixed(1)}%
              </Text>
            )}
          </Space>
        </div>
      </Card>
    </div>
  );
};

export default MessageBubble;
